package com.example.birdfriends.utils.files;

import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class FileService {
    public void removeListElem(List<String> list, String removeElem){  // 删除图片
        int len = list.size();
        for(int i = 0; i < len; i++){
            Object elem = list.get(i);
            if(Objects.equals(elem, removeElem)){
                list.remove(i);
                deleteImageInFolder(removeElem);
                len--;
                i--;
            }
        }
    }

    public void deleteFolder(String path){
        // 删除帖子或者词条时，需要同时删除对应的文件夹
        File file = new File(path);
        if(!file.exists()) return;

        File[] fileList = file.listFiles();   // 获取当前文件夹下的所有文件
        for (File f: fileList){
            if(f.isDirectory()){
                deleteFolder(f.getPath());
                if (f.delete()){
                    System.out.println("删除文件成功："+f.getPath());
                }else {
                    System.out.println("删除文件失败："+f.getPath());
                }
            }else {
                if (f.delete()){
                    System.out.println("删除文件成功："+f.getPath());
                }else {
                    System.out.println("删除文件失败："+f.getPath());
                }
            }
        }

        if (file.delete()){
            System.out.println("删除文件成功："+file.getPath());
        }else {
            System.out.println("删除文件失败："+file.getPath());
        }
    }

    private void deleteImageInFolder(String file){  // 删除图片
        String[] fileArr = file.split("8");
        String filepath = "D:/bf-files/springboot-upload"+fileArr[fileArr.length-1];
        System.out.println(filepath);
        File file1 = new File(filepath);
        System.out.println(file1.getAbsolutePath());

        if(file1.delete()){
            System.out.println("删除文件成功，"+file1.getAbsolutePath());
        }
    }

    public List<String> imageTypes(){
        List<String> types = new ArrayList<>();
        types.add("jpg");
        types.add("png");
        types.add("gif");
        types.add("tif");
        return types;
    }

    public List<String> videoTypes(){
        List<String> types = new ArrayList<>();
        types.add("mp4");
        types.add("avi");
        types.add("wmv");
        types.add("flv");
        return types;
    }
}
